<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    用Python操作Kubernetes的Job.md |  
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-develop/用Python操作Kubernetes的Job"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  用Python操作Kubernetes的Job.md
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/11/11/develop/%E7%94%A8Python%E6%93%8D%E4%BD%9CKubernetes%E7%9A%84Job/" class="article-date">
  <time datetime="2020-11-10T16:00:00.000Z" itemprop="datePublished">2020-11-11</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/develop/">develop</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.1k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">9 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h1 id="用Python操作Kubernetes的Job"><a href="#用Python操作Kubernetes的Job" class="headerlink" title="用Python操作Kubernetes的Job"></a>用Python操作Kubernetes的Job</h1><p>关于Kubernetes的Python SDK，几乎只有官方项目的examples。关于Job的基本增删改查操作，可以参考job_crud.py。但是，这只是基本用法，缺乏一些实用细节。  </p>
<p>本文给出Python SDK操作Kubernetes Job的更多示例代码，以及相关解释。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">pip install kubernetes  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">from kubernetes.client import BatchV1Api  </span><br><span class="line">from kubernetes.config import load_kube_config  </span><br><span class="line">  </span><br><span class="line">load_kube_config()  </span><br><span class="line">batch &#x3D; BatchV1Api()  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><code>load_kube_config</code>是从默认位置，也就是<code>~/.kube/config</code>加载配置。如果在其它位置，可以通过第一个参数传入其路径。</p>
<p><code>BatchV1Api()</code>可以当做Job的客户端来用。命名上，Batch和Job是类似的概念，前者强调批量。</p>
<h3 id="创建Job"><a href="#创建Job" class="headerlink" title="创建Job"></a>创建Job</h3><p>以下来自官方样例job_crud.py。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">def create_job_object():  </span><br><span class="line">      </span><br><span class="line">    container &#x3D; client.V1Container(  </span><br><span class="line">        ,  </span><br><span class="line">        image&#x3D;&quot;perl&quot;,  </span><br><span class="line">        command&#x3D;[&quot;perl&quot;, &quot;-Mbignum&#x3D;bpi&quot;, &quot;-wle&quot;, &quot;print bpi(2000)&quot;])  </span><br><span class="line">      </span><br><span class="line">    template &#x3D; client.V1PodTemplateSpec(  </span><br><span class="line">        metadata&#x3D;client.V1ObjectMeta(labels&#x3D;&#123;&quot;app&quot;: &quot;pi&quot;&#125;),  </span><br><span class="line">        spec&#x3D;client.V1PodSpec(restart_policy&#x3D;&quot;Never&quot;, containers&#x3D;[container]))  </span><br><span class="line">      </span><br><span class="line">    spec &#x3D; client.V1JobSpec(  </span><br><span class="line">        template&#x3D;template,  </span><br><span class="line">        backoff_limit&#x3D;4)  </span><br><span class="line">      </span><br><span class="line">    job &#x3D; client.V1Job(  </span><br><span class="line">        api_version&#x3D;&quot;batch&#x2F;v1&quot;,  </span><br><span class="line">        kind&#x3D;&quot;Job&quot;,  </span><br><span class="line">        metadata&#x3D;client.V1ObjectMeta(name&#x3D;JOB_NAME),  </span><br><span class="line">        spec&#x3D;spec)  </span><br><span class="line">  </span><br><span class="line">    return job  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">def create_job(api_instance, job):  </span><br><span class="line">    api_response &#x3D; api_instance.create_namespaced_job(  </span><br><span class="line">        body&#x3D;job,  </span><br><span class="line">        namespace&#x3D;&quot;default&quot;)  </span><br><span class="line">    print(&quot;Job created. status&#x3D;&#39;%s&#39;&quot; % str(api_response.status))  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>虽然，根据官方教程这样的写法，也能得到可用的<code>V1Job</code>，拿去执行创建操作。但还是过于陌生和偏门，不如主流、常见的YAML方便、易读写。</p>
<p>这里该出两种更方便的做法。</p>
<h3 id="直接使用YAML"><a href="#直接使用YAML" class="headerlink" title="直接使用YAML"></a>直接使用YAML</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">---  </span><br><span class="line">apiVersion: batch&#x2F;v1  </span><br><span class="line">kind: Job  </span><br><span class="line">metadata:  </span><br><span class="line">  name: hello  </span><br><span class="line">spec:  </span><br><span class="line">  template:  </span><br><span class="line">    spec:  </span><br><span class="line">      containers:  </span><br><span class="line">        - name: echo  </span><br><span class="line">          image: alpine:3.11  </span><br><span class="line">          args:  </span><br><span class="line">            - &#39;echo&#39;  </span><br><span class="line">            - &#39;Hello world!&#39;  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>以上是一个最精简的Job配置样例，</p>
<p>通过读取文件为dict，可以直接拿去使用。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">from kubernetes.client import V1Job  </span><br><span class="line">import yaml  </span><br><span class="line">  </span><br><span class="line">with open(&#39;job.yaml&#39;) as file:  </span><br><span class="line">    cfg &#x3D; yaml.safe_load(file)  </span><br><span class="line">job &#x3D; batch.create_namespaced_job(namespace&#x3D;&#39;default&#39;, body&#x3D;cfg)  </span><br><span class="line">assert isinstance(job, V1Job)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><code>create_namespaced_job</code>同样接受字典作为body输入，因此YAML配置可以读出后直接传入。</p>
<p>这里返回的<code>V1Job</code>只是创建时的状态，但是会包含更多集群中的信息。</p>
<h3 id="使用dict"><a href="#使用dict" class="headerlink" title="使用dict"></a>使用dict</h3><p>由于<code>create_namespaced_job</code>接受字典作为<code>body</code>输入，因此直接使用<code>dict</code>也是可行的。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">cfg &#x3D; &#123;  </span><br><span class="line">    &#39;apiVersion&#39;: &#39;batch&#x2F;v1&#39;,  </span><br><span class="line">    &#39;kind&#39;: &#39;Job&#39;,  </span><br><span class="line">    &#39;metadata&#39;: &#123;  </span><br><span class="line">        &#39;name&#39;: &#39;hello&#39;  </span><br><span class="line">    &#125;,  </span><br><span class="line">    &#39;spec&#39;: &#123;  </span><br><span class="line">        &#39;template&#39;: &#123;  </span><br><span class="line">            &#39;spec&#39;: &#123;  </span><br><span class="line">                &#39;restartPolicy&#39;:  </span><br><span class="line">                &#39;Never&#39;,  </span><br><span class="line">                &#39;containers&#39;: [&#123;  </span><br><span class="line">                    &#39;name&#39;: &#39;upload&#39;,  </span><br><span class="line">                    &#39;image&#39;: &#39;alpine:3.11&#39;,  </span><br><span class="line">                    &#39;args&#39;: [&#39;echo&#39;, &#39;Hello world!&#39;]  </span><br><span class="line">                &#125;]  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;  </span><br><span class="line">batch.create_namespaced_job(namespace&#x3D;&#39;default&#39;, body&#x3D;cfg)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>由于<code>dict</code>结构与YAML相同，而又没有类的束缚，所以也很灵活方便。</p>
<p>此外，从YAML读出为<code>dict</code>后，也可以通过修改部分字段，达到动态变化的效果。这种结合YAML和dict的使用方式，是对官方用法的最佳替代。</p>
<h3 id="监控Job运行"><a href="#监控Job运行" class="headerlink" title="监控Job运行"></a>监控Job运行</h3><p>在创建Job后，通常需要监控Job的运行，做一些外围处理。轮询当然是下下策，而Kubernetes提供了一个<code>Watch</code>机制，通过接收Event，实现对状态变化的掌控。Event只有在状态变化时才会有，所以是非常理想的回调。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">from kubernetes.client import V1Job  </span><br><span class="line">from kubernetes.watch import Watch  </span><br><span class="line">  </span><br><span class="line">job_name &#x3D; &#39;hello&#39;  </span><br><span class="line">watcher &#x3D; Watch()  </span><br><span class="line">for event in watcher.stream(  </span><br><span class="line">        batch.list_namespaced_job,  </span><br><span class="line">        namespace&#x3D;&#39;default&#39;,  </span><br><span class="line">        label_selector&#x3D;f&#39;job-name&#x3D;&#123;job_name&#125;&#39;,  </span><br><span class="line">):    </span><br><span class="line">    assert isinstance(event, dict)  </span><br><span class="line">    job &#x3D; event[&#39;object&#39;]  </span><br><span class="line">    assert isinstance(job, V1Job)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><code>Watch().stream</code>就是前面说的理想回调，它第一个参数是列出类的函数，这里选择<code>list_namespaced_job</code>。后面的参数，都是<code>list_namespaced_job</code>的参数。除了必备的namespace以外，<code>label_selector也</code>是一个常用参数，可以避免关注无关的Job。每个Job在创建后，都会自动带一个<code>f&#39;job-name=&#123;job_name&#125;&#39;</code>的Label，可以借此筛选。<code>job_name</code>就是<code>metadata</code>里设置的<code>name</code>，如这里<code>job-name=hello</code>。</p>
<p>event是一个dict，只有三个值。其中<code>event[&#39;raw_object&#39;]</code>只是<code>event[&#39;object&#39;]</code>的<code>dict</code>形式，没有太大意义。<code>event[&#39;type&#39;]</code>常见三个值，对应增删改。</p>
<ul>
<li><p><code>ADDED</code>，创建时的信息，和<code>create_namespaced_job</code>的返回值通常没有区别。</p>
</li>
<li><p><code>MODIFIED</code>，Job状态变化时的信息。</p>
</li>
<li><p><code>DELETED</code>，Job删除时的信息。</p>
</li>
</ul>
<p>以上三个状态值，对其它类型的资源也是通用的，比如Pod、Deployment等。</p>
<h3 id="V1Job的使用"><a href="#V1Job的使用" class="headerlink" title="V1Job的使用"></a>V1Job的使用</h3><p>对于具体的<code>V1Job</code>实例，其它字段都是和创建时的配置差不多的，只是多一些集群中的具体信息。所以，常用的还是.status字段。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; from kubernetes.client import V1JobStatus  </span><br><span class="line">&gt;&gt;&gt; isinstance(job.status, V1JobStatus)  </span><br><span class="line">True  </span><br><span class="line">&gt;&gt;&gt; print(job.status)  </span><br><span class="line">&#123;&#39;active&#39;: None,  </span><br><span class="line"> &#39;completion_time&#39;: datetime.datetime(2020, 8, 10, 9, 49, 38, tzinfo&#x3D;tzutc()),  </span><br><span class="line"> &#39;conditions&#39;: [&#123;&#39;last_probe_time&#39;: datetime.datetime(2020, 8, 10, 9, 49, 38, tzinfo&#x3D;tzutc()),  </span><br><span class="line">   &#39;last_transition_time&#39;: datetime.datetime(2020, 8, 10, 9, 49, 38, tzinfo&#x3D;tzutc()),  </span><br><span class="line">   &#39;message&#39;: None,  </span><br><span class="line">   &#39;reason&#39;: None,  </span><br><span class="line">   &#39;status&#39;: &#39;True&#39;,  </span><br><span class="line">   &#39;type&#39;: &#39;Complete&#39;&#125;],  </span><br><span class="line"> &#39;failed&#39;: None,  </span><br><span class="line"> &#39;start_time&#39;: datetime.datetime(2020, 8, 10, 9, 49, 32, tzinfo&#x3D;tzutc()),  </span><br><span class="line"> &#39;succeeded&#39;: 1&#125;  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>直接使用<code>job.status.succeeded</code>，可以得到成功的Container数量。下面几乎每一级都有特定的类，可以连续使用.操作符。如果有特殊需要，也可以用<code>job.to_dict()</code>转换成字典来用。</p>
<p>其它字段，作用基本上也和名称相关，不难推测。</p>
<h3 id="列出Job"><a href="#列出Job" class="headerlink" title="列出Job"></a>列出Job</h3><p>列出所有Job的<code>list_job_for_all_namespaces</code>不常用，一般只列出指定Namespace的Job。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">from kubernetes.client import V1JobList, V1Job  </span><br><span class="line">  </span><br><span class="line">job_list &#x3D; batch.list_namespaced_job(namespace&#x3D;&#39;default&#39;)  </span><br><span class="line">assert isinstance(job_list, V1JobList)  </span><br><span class="line">  </span><br><span class="line">assert isinstance(job_list.items, list)  </span><br><span class="line">for job in job_list.items:  </span><br><span class="line">    assert isinstance(job, V1Job)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>与监控的示例相比，这里去掉了<code>label_selector</code>，可以获取Namespace中所有的Job。如果有需要，可以通过自定义Label把所有Job分类，并使用l<code>abel_selector</code>获取指定类型的Job。</p>
<h3 id="读取Job"><a href="#读取Job" class="headerlink" title="读取Job"></a>读取Job</h3><p>如果知道Job的<code>name</code>，可以直接通过<code>read_*</code>系列接口，获得指定的<code>V1Job</code>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">from kubernetes.client import V1Job  </span><br><span class="line">  </span><br><span class="line">job &#x3D; batch.read_namespaced_job(name&#x3D;&#39;hello&#39;, namespace&#x3D;&#39;default&#39;)  </span><br><span class="line">assert isinstance(job, V1Job)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>如果更看重状态，可以改用<code>read_namespaced_job_status</code>。虽然访问的API不同，但在Python的<code>V1Job</code>这个结果层面，没有本质差异。</p>
<h3 id="列出一个Job的Pod"><a href="#列出一个Job的Pod" class="headerlink" title="列出一个Job的Pod"></a>列出一个Job的Pod</h3><p>Pod是Kubernetes调度的最小单元，也是最常用的一种资源。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">from typing import List  </span><br><span class="line">  </span><br><span class="line">from kubernetes.client import CoreV1Api, V1Pod  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">def get_pods_by(job_name: str) -&gt; List[V1Pod]:  </span><br><span class="line">    core &#x3D; CoreV1Api()  </span><br><span class="line">    pods &#x3D; core.list_namespaced_pod(  </span><br><span class="line">        namespace&#x3D;&#39;default&#39;,  </span><br><span class="line">        label_selector&#x3D;f&#39;job-name&#x3D;&#123;job_name&#125;&#39;,  </span><br><span class="line">        limit&#x3D;1,  </span><br><span class="line">    )  </span><br><span class="line">    return pods.items  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>这里的<code>get_pods_by</code>，可以用<code>job_name</code>获取对应的Pod。<code>limit=1</code>是在已知Pod只有一个的情况下做出的优化，可按需调整或去掉。</p>
<h3 id="删除Job"><a href="#删除Job" class="headerlink" title="删除Job"></a>删除Job</h3><p>删除一个Job：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">from kubernetes.client import V1Status  </span><br><span class="line">  </span><br><span class="line">status &#x3D; batch.delete_namespaced_job(  </span><br><span class="line">    namespace&#x3D;&#39;default&#39;,  </span><br><span class="line">    name&#x3D;job_name,  </span><br><span class="line">    propagation_policy&#x3D;&#39;Background&#39;,  </span><br><span class="line">)  </span><br><span class="line">assert isinstance(status, V1Status)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>其中，<code>propagation_policy=&#39;Background&#39;</code>是不可省略的关键，否则默认是<code>Orphan</code>，其Pod不会被删除。这属于API设计的一个失误，与<code>kubectl</code>的默认行为不符合。而且，应该没有人在删除了Job之后，还要保留Pod的吧。这里也可以选择<code>&#39;Foreground&#39;</code>，阻塞等待相关资源的删除完毕。</p>
<p>删除多个、或所有Job：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">status &#x3D; batch.delete_collection_namespaced_job(  </span><br><span class="line">    namespace&#x3D;&#39;default&#39;,  </span><br><span class="line">    propagation_policy&#x3D;&#39;Background&#39;,  </span><br><span class="line">    label_selector&#x3D;&#39;some-label&#x3D;your-value&#39;,  </span><br><span class="line">)  </span><br><span class="line">assert isinstance(status, V1Status)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>如果没有<code>label_selector</code>，那就是删除一个<code>Namespace</code>中的所有Job。</p>
<h3 id="更新Job"><a href="#更新Job" class="headerlink" title="更新Job"></a>更新Job</h3><p>这个比较少用，因为一般都是建新的。用法其实和<code>create_namespaced_job</code>差不多，参考官方样例即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">def update_job(api_instance, job):  </span><br><span class="line">      </span><br><span class="line">    job.spec.template.spec.containers[0].image &#x3D; &quot;perl&quot;  </span><br><span class="line">    api_response &#x3D; api_instance.patch_namespaced_job(  </span><br><span class="line">        name&#x3D;JOB_NAME,  </span><br><span class="line">        namespace&#x3D;&quot;default&quot;,  </span><br><span class="line">        body&#x3D;job)  </span><br><span class="line">    print(&quot;Job updated. status&#x3D;&#39;%s&#39;&quot; % str(api_response.status))  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>用Python操作Kubernetes的Job，总体上还是比较方便的。</p>
<p>作者：匿蟒</p>
<p>原文链接：<a target="_blank" rel="noopener" href="https://note.qidong.name/2020/08/python-k8s-job/">https://note.qidong.name/2020/08/python-k8s-job/</a></p>
<p>END</p>
<hr>
<p>                                </p>
<p>            **点击如下图片，了解<br>**</p>
<p>      运维+测试+开发+架构全栈进阶之路  </p>
<hr>
<h2 id="技术交流"><a href="#技术交流" class="headerlink" title="技术交流"></a>技术交流</h2><p>学无止境，了解更多关于kubernetes/docker/devops/openstack/openshift/linux/IaaS/PaaS相关内容，想要获取更多资料和免费视频，可按如下方式进入技术交流群</p>
<p><img src=""></p>
<p><strong>微信：</strong>luckylucky421302  </p>
<p>微信公众号  </p>
<hr>
<p> <strong>长按指纹关注公众号</strong>👇**<br>**</p>
<p><img src="">              </p>
<p>往期精彩文章  </p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzU0NjEwMTg4Mg==&mid=2247484708&idx=1&sn=2a7230ade0ce0bd9059e92752e03ba18&chksm=fb638a31cc14032772d778f1a8fa5dc73f9aba6c99546c9ab25d9f91f706be3cff34572f0c1a&scene=21#wechat_redirect">kubernetes全栈技术+企业案例演示【带你快速掌握和使用k8s】</a></p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzU0NjEwMTg4Mg==&mid=2247486272&idx=1&sn=e993bc259db899b79922863859d24bb2&chksm=fb638455cc140d43dd091b09efc0c744b82f32d905c78ce9be71aae8c6d324d625f110fa1093&scene=21#wechat_redirect">突破运维和开发瓶颈、Python、k8s、DevOps转型一网打尽！</a></p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzU0NjEwMTg4Mg==&mid=2247487181&idx=1&sn=8cb290c13cc5d7bec65abac1a668e6be&chksm=fb6381d8cc1408cee263ae5c2d8d63c899001eb45a56197f5480ef66e9998d1e9cd15e203e0c&scene=21#wechat_redirect">运维+测试+开发+架构进阶之路</a>  </p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzU0NjEwMTg4Mg==&mid=2247486031&idx=1&sn=58003addbf36f2858f7d0dfbf887bb2a&chksm=fb63855acc140c4cf0346cc3433bc874e7cd37a5b17cf5254147a1b20b538cf70158f2234b0f&scene=21#wechat_redirect">python运维开发实战-基础篇  
</a></p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzU0NjEwMTg4Mg==&mid=2247486201&idx=1&sn=0d45a2660a7480d73cf72ba67fe52f3a&chksm=fb6385eccc140cfa90bef6759c768c94ac2ca904c827fb2dcd969858ba46b818145e76e09c62&scene=21#wechat_redirect">python运维和开发实战-高级篇</a>  </p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzU0NjEwMTg4Mg==&mid=2247486210&idx=1&sn=078e172a34c22e5db1f57b17c21b2efe&chksm=fb638417cc140d011a058d7cf83795bf75cfc327acbb3727c968058ff2807874a26f87843080&scene=21#wechat_redirect">python运维和开发实战-安装和创建Django项目</a></p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzU0NjEwMTg4Mg==&mid=2247484220&idx=1&sn=72ae437836108fbecbeb86752aad888c&chksm=fb638c29cc14053fafcb62be244f5a279052b8d159c9c530e73495cfd8ab97205988780d4aaa&scene=21#wechat_redirect">谈谈我的IT发展之路</a></p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzU0NjEwMTg4Mg==&mid=2247484445&idx=1&sn=bf8928e7aae815b8e7f9ac56a67289ce&chksm=fb638b08cc14021e5e025f2f0b89d18ec5ef19f9dec4429a56f356e8b596d01095e313dab3e3&scene=21#wechat_redirect">Prometheus+Grafana+Alertmanager搭建全方位的监控告警系统-超详细文档</a></p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzU0NjEwMTg4Mg==&mid=2247484264&idx=1&sn=4d74de0cb117c07ba7c73ea21c42bf94&chksm=fb638c7dcc14056b9f0261e05e4d36a057c4511fb5806222f71b7965c3573fed86672b2c93b7&scene=21#wechat_redirect">k8s1.18多master节点高可用集群安装-超详细中文官方文档</a></p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzIzOTQ3NDg1Mw==&mid=2247483668&idx=1&sn=a7d0768b7eb034ef2e2f23e25b1b1845&chksm=e928c0dede5f49c878898e04329f08d8adf554397476283aaa3f2554f71a8bf20986755fbcc9&scene=21#wechat_redirect">linux面试题汇总</a></p>
<p><a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzU0NjEwMTg4Mg==&mid=2247486210&idx=1&sn=078e172a34c22e5db1f57b17c21b2efe&chksm=fb638417cc140d011a058d7cf83795bf75cfc327acbb3727c968058ff2807874a26f87843080&scene=21#wechat_redirect">python运维和开发实战-安装和创建Django项目</a></p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2020/11/11/develop/%E7%94%A8Python%E6%93%8D%E4%BD%9CKubernetes%E7%9A%84Job/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/develop/" rel="tag">develop</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/11/11/develop/%E6%8E%A8%E8%8D%90%E8%BF%99%E6%AC%BE%E5%BC%80%E6%BA%90%E3%80%81%E8%BD%BB%E9%87%8F%E6%97%A0%20Agent%20%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E5%B9%B3%E5%8F%B0/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            推荐这款开源、轻量无 Agent 自动化运维平台.md
          
        </div>
      </a>
    
    
      <a href="/2020/11/11/develop/%E7%9B%B8%E8%A7%81%E6%81%A8%E6%99%9A%EF%BC%81Python%E9%82%A3%E4%BA%9B%E4%B8%8D%E4%B8%BA%E4%BA%BA%E7%9F%A5%E7%9A%84%E5%A4%A7%E5%9D%91/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">相见恨晚！Python那些不为人知的大坑.md</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> TzWind
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Hexo"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" target="_blank" rel="noopener" href="http://www.baidu.com">百度</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2019/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>